<template>
    <view class="home">
        <MakeFriends :activeVal="state.active" v-if="state.active == 0"></MakeFriends>
        <Square :activeVal="state.active" v-if="state.active == 1"></Square>
        <MessageNoticeBox :activeVal="state.active" v-if="state.active == 3"></MessageNoticeBox>
        <PersonBox :activeVal="state.active" v-if="state.active == 4"></PersonBox>
        <van-tabbar v-model="state.active" @change="onChange">
            <van-tabbar-item icon="home-o" v-for="(item,index) in state.barList" :key="item.id" >
                <!-- :badge="curMessageNum" -->
                <span>{{ item.name }}</span>
                <template #icon="props">
                    <div class="icon-box">
                        <van-badge v-if="index == 3 && curMessageNum" :content="curMessageNum" class="badge-box"></van-badge>
                    <img :src="props.active ? item.icon : item.icon_gray" />
                    </div>
                </template>
            </van-tabbar-item>
        </van-tabbar>
        <!-- <button @click="sendFn">fasong</button> -->
    </view>
</template>

<script setup>
import { reactive, getCurrentInstance, onMounted, computed } from "vue"
import { getAuthorization, setAuthorization } from "@/utils/auth.js"

import MakeFriends from "@/pages/home/makeFriends"
import Square from "@/pages/home/square"
import MessageNoticeBox from "@/pages/home/message"
import PersonBox from "@/pages/home/person"
import bar01 from '@/assets/image/bar01.png'
import bar01_gray from '@/assets/image/bar01_grad.png'
import bar02 from '@/assets/image/bar02.png'
import bar02_gray from '@/assets/image/bar02_grad.png'
import bar03 from '@/assets/image/bar03.png'
import bar04 from '@/assets/image/bar04.png'
import bar04_gray from '@/assets/image/bar04_grad.png'
import bar05 from '@/assets/image/bar05.png'
import bar05_gray from '@/assets/image/bar05_grad.png'

import { onLoad } from '@dcloudio/uni-app'

let { proxy } = getCurrentInstance()

const state = reactive({
    active: 0,
    barList: [
        {
            id: 1,
            name: '交友',
            icon: bar01,
            icon_gray: bar01_gray
        },
        {
            id: 2,
            name: '广场',
            icon: bar02,
            icon_gray: bar02_gray
        },
        {
            id: 3,
            name: '',
            icon: bar03,
            icon_gray: bar03
        },
        {
            id: 4,
            name: '消息',
            icon: bar04,
            icon_gray: bar04_gray
        },
        {
            id: 5,
            name: '我的',
            icon: bar05,
            icon_gray: bar05_gray
        }
    ],
})

onLoad((option) => {
    let active = getAuthorization("active")
    state.active = active
})

const onChange = (index) => {
    console.log(index)
    if (index == 2) {
        uni.navigateTo({
            url: '/pages/home/releaseDynamic/index'
        })
    } else {
        setAuthorization("active", index)
    }
};

import {
    UserRealAuth
} from "@/api/person/index.js"

import { AuthStateStore } from "@/store/authIndex.js"
let AuthStore = AuthStateStore()

const UserRealAuthFn = async () => {
    let data = await proxy.$get(UserRealAuth)
    if (data.code == 200) {
        AuthStore.updateState(data.data)
    }
}

onMounted(() => {
    UserRealAuthFn()
    getUserInfo()
})

// 获取用户信息
import {
    UserInfo
} from "@/api/person/index.js"

const getUserInfo = async () => {
    let data = await proxy.$get(UserInfo + getAuthorization('userId'))
    if (data.code == 200) {
        setAuthorization("userInfo", JSON.stringify(data.data))
        // nimFn()
    }

}
// let token = getAuthorization("token")
// if (!token) {
//     uni.navigateTo({
//         url: "/pages/login/mobileNumberLogin/index"
//     })
// }
import q1 from "@/assets/image/icon21.png"
import q2 from "@/assets/image/icon20.png"
let avatarList = {
    '钱包消息':q1,
    '系统消息':q2
}

// ------im
import {
    IMUserInfo
} from "@/api/im/index.js"
import SDK from "@yxim/nim-web-sdk";
import { useAccountStore } from "@/store/index.js"
let store = useAccountStore()
const onMsg = async (msg) => {
    let makeFriendsList = store.$state.makeFriendsList
    let arr = makeFriendsList.map(o => o.IMId)
    msg.chatType = 1
    msg.isRead = 1
    msg.msgUserId = getAuthorization('userId')
    console.log(store, 'store1111',msg)
    if (!arr.includes(msg.from)) {
        if(msg.from != "100169" && msg.from != "100170" && msg.from != "100171"){
            let data = await proxy.$get(IMUserInfo + msg.from)
            data.data.UserInfo.msgUserId = msg.msgUserId
            store.addMakeFriends(data.data.UserInfo)
        }else{
            let otherUser = {
                Avatar:avatarList[msg.fromNick],
                ShowName:msg.fromNick,
                ID:msg.from,
                IMId:msg.from,
                isHide:true,
                msgUserId:msg.msgUserId
            }
            msg.content = JSON.parse(msg.content)
            msg.text = msg.pushContent
            store.addMakeFriends(otherUser)
        }
    }
    store.addChatMsg(msg)
    console.log(store, 'store1111',msg)
    // pushMsg(msg);
    // switch (msg.type) {
    //     case "custom":
    //         // onCustomMsg(msg);
    //         break;
    //     case "notification":
    //         // onTeamNotificationMsg(msg);
    //         break;
    //     // 其它case
    //     default:
    //         break;
    // }
}

    let curUserInfo = JSON.parse(getAuthorization("userInfo"))
    let IMId = curUserInfo.IMId
    let IM_ToKen = curUserInfo.IM_ToKen
    if(IMId){
        proxy.nim = SDK.NIM.getInstance({
            debug: true, // 是否开启日志，将其打印到console。集成开发阶段建议打开。
            appKey: "181791f825dd689e4daac44fb7870ce4",
            account: IMId, //用于登录IM
            token: IM_ToKen, //用于登录IM
            db: true, //若不要开启数据库请设置false。SDK 默认为true。
            // privateConf: {}, // 私有化部署方案所需的配置
            // onconnect: onConnect,
            //消息收发的监听事件
            onmsg: onMsg,
        });
    }

    
const curMessageNum = computed(() => {
    let arr = store.$state.chatListAll.filter(o => o.isRead == 1 )
    return arr.length
})
// const sendFn = () => {
//     // let store = useAccountStore()
//     // store.login(5)
//     proxy.nim.sendText({
//         scene: "p2p",
//         to: "251707",
//         text: "优秀11111111111111111111",
//         done: sendMsgDone,
//     });
//     getF()
// };

// function sendMsgDone(error, msg) {
//     console.log(error);
//     console.log(msg);
//     console.log(
//         "发送" +
//         msg.scene +
//         " " +
//         msg.type +
//         "消息" +
//         (!error ? "成功" : "失败") +
//         ", id=" +
//         msg.idClient
//     );
// }

</script>

<style lang="scss" scoped>
.header-tab-left {
    display: flex;
    align-items: flex-end;
    padding: 20rpx;

    .header-tab-item {
        width: 100rpx;
        font-size: 32rpx;
        font-weight: 400;
        color: #999999;
        line-height: 38rpxpx;
        text-align: center;
    }

    .header-tab-item-cur {
        font-size: 44rpx;
        font-weight: bold;
        color: #262626;
    }
}
.icon-box{
    position: relative;
}
.badge-box{
    position: absolute;
    top:0;
   transform: translate(50%,-50%);
}
</style>